package com.D5Power.Editor.EditorWindow
{
	import com.adobe.images.JPGEncoder;
	import com.adobe.images.PNGEncoder;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.FileFilter;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import org.aswing.AssetBackground;
	import org.aswing.ButtonGroup;
	import org.aswing.DefaultBoundedRangeModel;
	import org.aswing.JButton;
	import org.aswing.JCheckBox;
	import org.aswing.JLabel;
	import org.aswing.JPanel;
	import org.aswing.JProgressBar;
	import org.aswing.JRadioButton;
	import org.aswing.JTextField;
	import org.aswing.SoftBoxLayout;
	import org.aswing.ext.Form;

	public class MapCut extends D5EditorWin
	{
		private var _fileName:JTextField;
		
		/**
		 * 缩略图
		 */ 
		private var _show:JPanel;
		
		/**
		 * 源数据
		 */ 
		private var _resource:Bitmap;
		private var smallMap:BitmapData;
		
		private var _winWidth:uint = 200;
		
		private var main:JPanel;
		
		private var _codetype_png:JRadioButton;
		private var	_codetype_jpg:JRadioButton;
		
		private var _loopy:uint;
		private var _loopx:uint;
		
		private var _progressbar:JProgressBar;
		
		public function MapCut(owner:MapEditor)
		{
			mytitle = '地图切割';
			super(owner);
		}
		
		override protected function init():void
		{
			_box = new Form();
			main = new JPanel(new SoftBoxLayout(SoftBoxLayout.Y_AXIS));
			
			_fileName = new JTextField('',8);
			var lab0:JLabel = new JLabel('选择文件：');
			var bt0:JButton = new JButton('打开');
			bt0.addActionListener(openMap);
			
			var lab1:JLabel = new JLabel('编码类型：');
			
			_codetype_png = new JRadioButton('PNG');
			_codetype_png.setSelected(true);
			_codetype_jpg = new JRadioButton('JPG');
			var gp:ButtonGroup = new ButtonGroup();
			gp.appendAll(_codetype_png,_codetype_jpg);
			
			
			_show = new JPanel();
			
			_progressbar = new JProgressBar(JProgressBar.HORIZONTAL);
			_progressbar.setModel(new DefaultBoundedRangeModel(0,100));
			
			_box.addRow(lab0,_fileName,bt0);
			_box.addRow(lab1,_codetype_png,_codetype_jpg);
			_box.setSizeWH(_winWidth,260);
			
			main.append(_box);
			main.append(_progressbar);
			main.append(_show);
			getContentPane().append(main);
			super.init();
		}
		
		private function openMap(e:Event):void
		{
			var file_open:File = File.desktopDirectory;
			file_open.browseForOpen('打开地图配置文件', [new FileFilter('图片', '*.jpg;*.gif;*.png' )] );
			file_open.addEventListener(Event.SELECT,onOpen);
		}
		
		private function onOpen(e:Event):void
		{
			var file:File = e.target as File;
			
			_fileName.setText(file.name);
			
			var fs:FileStream = new FileStream();
			var bytes:ByteArray = new ByteArray();
			fs.open(file,FileMode.READ);
			fs.readBytes(bytes,0,fs.bytesAvailable);
			fs.close();
			
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onMapComplate);
			loader.loadBytes(bytes);
		}
		
		private function onMapComplate(e:Event):void
		{
			var target:LoaderInfo = e.target as LoaderInfo;
			_resource = target.loader.content as Bitmap;
			
			if(_resource.width!=Global.MAPSIZE.x || _resource.height!=Global.MAPSIZE.y)
			{
				_root.msg('提示','您选择的图片尺寸与当前地图的尺寸不符!');
				target.loader.unload();
				_resource.bitmapData.dispose();
				_resource = null;
				return;
			}
			
			var _b_width:uint = _winWidth-_padding*2;
			var _b_height:uint = int(_resource.height*(_b_width/_resource.width));
			
			if(smallMap!=null) smallMap.dispose();
			smallMap = new BitmapData(_b_width,_b_height);
			smallMap.draw(_resource,new Matrix(_b_width/_resource.width,0,0,_b_height/_resource.height)); // 读取成功，绘制缩略图
			
			target.loader.unload();
			
			_show.setSizeWH(_b_width,_b_height);
			_show.setBackgroundDecorator(new AssetBackground(new Bitmap(smallMap)));
		}
		
		override protected function onSubmit(e:Event):void
		{
			if(e==null)
			{
				// 当文件创建完成后回调，此时e为null
				super.onSubmit(e);
				return;
			}
			if(_resource == null) return;

			_loopy = 0;
			_loopx = 0;
			
			// 产生缩略图
			var encoder:JPGEncoder = new JPGEncoder();
			var bytes:ByteArray = encoder.encode(smallMap);
			var writer:File = new File(File.applicationDirectory.resolvePath('asset/tiles/'+_root.Shower.scene.Map.mapid+'/s.jpg').nativePath);
			var fs:FileStream = new FileStream();
			fs.open(writer,FileMode.WRITE);
			fs.writeBytes(bytes,0,bytes.bytesAvailable);
			fs.close();
			
			var t:Timer = new Timer(50);
			t.addEventListener(TimerEvent.TIMER,makeFile);
			t.start();
		}
		
		/**
		 * 切割文件
		 */ 
		private function makeFile(e:Event):void
		{
			var _tile_max_x:uint = Math.ceil(Global.MAPSIZE.x/Global.TILE_SIZE.x);
			var _tile_max_y:uint = Math.ceil(Global.MAPSIZE.y/Global.TILE_SIZE.y);
			
			var mapid:uint = _root.Shower.scene.Map.mapid;
			
			var expName:String;
			var file:File = new File(File.applicationDirectory.resolvePath('asset/tiles/'+mapid).nativePath);
			file.createDirectory();
			
			var encoder:JPGEncoder = new JPGEncoder();
			var fs:FileStream = new FileStream();
			
			var bitmap:BitmapData = new BitmapData(Global.TILE_SIZE.x,Global.TILE_SIZE.y,false,0);
			bitmap.copyPixels(_resource.bitmapData,new Rectangle(_loopx*Global.TILE_SIZE.x,_loopy*Global.TILE_SIZE.y,Global.TILE_SIZE.x,Global.TILE_SIZE.y),new Point());
			
			var bytes:ByteArray;
			if(_codetype_png.isSelected())
			{
				bytes = PNGEncoder.encode(bitmap);
				expName = '.png';
			}else{
				bytes = encoder.encode(bitmap);
				expName = '.jpg';
			}
			
			// 写入文件
			var writer:File = new File(File.applicationDirectory.resolvePath('asset/tiles/'+mapid+'/'+_loopy+'_'+_loopx+expName).nativePath);
			
			fs.open(writer,FileMode.WRITE);
			fs.writeBytes(bytes,0,bytes.bytesAvailable);
			fs.close();
			
			_progressbar.setValue(int(100*(_loopy*_tile_max_x+_loopx)/(_tile_max_x*_tile_max_y)));
			
			_loopx++;

			if(_loopx>=_tile_max_x)
			{
				_loopx=0;
				_loopy++;
				if(_loopy>=_tile_max_y)
				{
					onSubmit(null);
					(e.target as Timer).stop();
					(e.target as Timer).removeEventListener(TimerEvent.TIMER,makeFile);
					_root.MapProp.setSceneBG(expName);
				}
			}
		}
	}
}